<?php
/**
 * Created by PhpStorm.
 * User: am
 * Date: 16/9/27
 * Time: 上午11:08
 */

namespace Common\Libiary;

class BillHttp{

    public $header = array (
        'content-type:application/x-www-form-urlencoded;charset=utf-8'
    );

    private $jkversion = 'V1';
    private $appid = 103;

    public function __construct() {
    }

    // 发送请求
    public function CurlHttp($service, $data=array(), $url='', $header=array()) {

        $data = $this->curlData($data);
        $url = empty($url)? BASE_SHOP_INFO_COO_URL :$url;
        $URL = $url.$service;

        $curl = curl_init ();
        if (!empty($header)) {
            curl_setopt ( $curl, CURLOPT_HTTPHEADER, $header );
        } else {
            curl_setopt ( $curl, CURLOPT_HTTPHEADER, $this->header );
        }

        curl_setopt ( $curl, CURLOPT_URL, $URL);
        curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $curl, CURLOPT_TIMEOUT, 5 );
        curl_setopt ( $curl, CURLOPT_POST, 1 );
        if (!empty($header)) {
            curl_setopt ( $curl, CURLOPT_POSTFIELDS, $data);
        } else {
            curl_setopt ( $curl, CURLOPT_POSTFIELDS, http_build_query($data));
        }

        $output = curl_exec ( $curl );
        $status = curl_getinfo ( $curl );
        $info = curl_getinfo ( $curl );
        curl_close ( $curl );

        return $output;
    }

    private function curlData($data){

        $base = array(
            'time' => time(),
            'jkversion' => $this->jkversion,
            'nonce' => mt_rand(10000,99999),
            'appid' => $this->appid

        );

        $data = array_merge($base,$data);

        $data['sign'] = $this->createSign($data);

        return $data;
    }


    // 生成签名
    private function createSign($data) {
        if (isset($data['sign'])) unset($data['sign']);

        ksort($data);
        $str = '';
        foreach($data as $key=>$value){
            if (is_object($value) || is_array($value)) {
                continue;
            }
            $str .= $key . $value;
        }
        $str .= BASE_SHOP_INFO_CODE;
        $sign = md5($str);

        return $sign;
    }
}